package com.charon.common.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @ClassName: ImageCodeUtils
 * @Description: 图形验证码生成工具类
 * @Author Charon [248135724@qq.com]
 * @Date 2019/2/7 2:49
 * @Version V 1.0
 */
public class ImageCodeUtils {
    /**
     * 默认颜色最大值
     */
    public final static int DEFAULT_MAX_COLOR=255;
    /**
     * 默认图形宽度
     */
    public final static int DEFAULT_WIDTH=67;
    /**
     * 默认图形高度
     */
    public final static int DEFAULT_HEIGHT=23;


    /**
     * Description: 生成验证码图片
     * <p>Author: Charon [248135724@qq.com]
     * @Date 2019/2/7 3:09
     * @param width 验证码图片宽度
     * @param height 验证码图片高度
     * @return com.charon.common.entity.ImageCode
     */
    public static BufferedImage createImageCode(Integer width,Integer height,String validateCode){
        if(!StringUtils.isEmpty(validateCode))return null;
        if (width == null|| width == 0) width=DEFAULT_WIDTH;
        if (height == null|| height == 0) height=DEFAULT_HEIGHT;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();
        // 生成画布
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        for (int i = 0; i <validateCode.length(); i++) {
            String rand = String.valueOf(validateCode.charAt(i));
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),
                    20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }
        g.dispose();
        return image;
    }


    /**
     * 生成随机背景条纹
     * @param fc 前景色
     * @param bc 背景色
     * @return RGB颜色
     */
    private static Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc < 0 || fc > DEFAULT_MAX_COLOR) {
            fc = DEFAULT_MAX_COLOR;
        }
        if (bc < 0 || bc > DEFAULT_MAX_COLOR) {
            bc = DEFAULT_MAX_COLOR;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
